package com.itany.cloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Author:shixiaojun@itany.com
 * Date: 2022/3/23 13:32
 * Version: 1.0-SNAPSHOT
 */
@Component
public class LogFilter implements GlobalFilter, Ordered {

    /**
     * 定义过滤器的具体实现
     * @param exchange
     * @param chain
     * @return 判断当前过滤器是否放行
     *          若返回值为null,表示不放行
     *          若需要放行,通过GatewayFilterChain参数调用filter方法进行放行
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("LogFilter.filter");
        // 获取请求中key为username的参数的值
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if(null == username || "".equals(username)){
            System.out.println("用户名不能为空");
            // 不放行
            return null;
        }
        // 放行
        return chain.filter(exchange);
    }

    /**
     * 定义过滤器的优先级
     * 在Ordered接口中定义了其值的范围
     * 值越小,优先级越高
     * 其最小值为:-2147483648
     * 其最大值为:2147483647
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
